const {
  selectAll,
  modifyService,
  addService,
  queryInfoService,
  deleteService,
  deleteSelectService,
} = require("../service/category.service");
const {
  CateModifyError,
  CateAddError,
  DeleteError,
} = require("../constant/err.type");
class UserController {
  // 查询列表
  async queryList(ctx, next) {
    // 2.操作数据库
    console.log(ctx.request.body, "??");
    const res = await selectAll(ctx.request.body);
    console.log(res, "cate");
    const { data, pageSize, currentPage, total } = res;
    ctx.body = {
      code: 0,
      messgae: "success",
      data: {
        cateList: data,
        pageSize,
        currentPage,
        total,
        totalPage: Math.ceil(total / pageSize),
      },
    };
  }
  // 按id修改数据
  async modifyControl(ctx, next) {
    const { typeName, icon, id } = ctx.request.body;
    try {
      const [effectid, row] = await modifyService({ typeName, icon, id });
      console.log(effectid, row, "----");
      if (row >= 0) {
        ctx.body = {
          code: 200,
          messgae: "success",
          data: null,
        };
      } else {
        ctx.app.emit("error", CateModifyError, ctx);
      }
    } catch (error) {
      console.error(error);
      ctx.app.emit("error", CateModifyError, ctx);
    }
  }

  // 添加cate
  async addControl(ctx, next) {
    const { typeName, icon } = ctx.request.body;
    try {
      const [effectid, row] = await addService({ typeName, icon });
      // console.log(effectid, row, "----");
      if (row > 0) {
        ctx.body = {
          code: 200,
          messgae: "success",
          data: null,
        };
      } else {
        ctx.app.emit("error", CateAddError, ctx);
      }
    } catch (error) {
      console.error(error);
      ctx.app.emit("error", CateAddError, ctx);
    }
  }

  // 按id查询信息
  async queryInfoControl(ctx, next) {
    const { id } = ctx.query;
    console.log(id, "--id");
    const res = await queryInfoService(id);
    console.log(res, "---res--");
    ctx.body = {
      code: 200,
      message: "查询成功！",
      data: res,
    };
  }

  async deleteControl(ctx, next) {
    const id = ctx.request.body.id;
    try {
      const res = await deleteService(id);
      ctx.body = {
        code: 200,
        messgae: "删除成功!",
        data: null,
      };
    } catch (error) {
      ctx.app.emit("error", DeleteError, ctx);
      return;
    }
  }
  7;

  async deleteSelectControl(ctx, next) {
    const ids = ctx.request.body.ids.split(",");
    try {
      await deleteSelectService(ids);
      ctx.body = {
        code: 200,
        messgae: "删除成功!",
        data: null,
      };
    } catch (error) {
      ctx.app.emit("error", DeleteError, ctx);
      return;
    }
  }
}

module.exports = new UserController();
